<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI模拟面试 - 实时聊天</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.0/dist/jquery.min.js"></script>
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #7209b7;
            --accent-color: #f72585;
            --background-color: #f8f9fa;
            --text-color: #333;
            --light-gray: #e9ecef;
            --border-radius: 12px;
            --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            --user-message-bg: #4361ee;
            --user-message-text: white;
            --ai-message-bg: white;
            --ai-message-text: #333;
            --typing-indicator-color: #6c757d;
        }

        body {
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background-color: var(--background-color);
            color: var(--text-color);
            line-height: 1.6;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .header {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            padding: 1rem 0;
            box-shadow: var(--box-shadow);
        }

        .header h1 {
            font-weight: 600;
            margin-bottom: 0.5rem;
            font-size: 1.75rem;
        }

        .header-info {
            font-size: 0.875rem;
            opacity: 0.9;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            flex: 1;
            padding: 20px;
        }

        .interview-container {
            display: flex;
            flex-direction: column;
            height: calc(100vh - 180px);
            margin-top: 1.5rem;
            margin-bottom: 1.5rem;
        }

        .interview-info {
            background: white;
            border-radius: var(--border-radius) var(--border-radius) 0 0;
            box-shadow: var(--box-shadow);
            padding: 1rem 1.5rem;
            border-bottom: 1px solid var(--light-gray);
        }

        .chat-messages {
            flex: 1;
            background: white;
            overflow-y: auto;
            padding: 1.5rem;
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }

        .message {
            max-width: 75%;
            padding: 1rem;
            border-radius: var(--border-radius);
            position: relative;
            word-wrap: break-word;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }

        .message.ai {
            background-color: var(--ai-message-bg);
            color: var(--ai-message-text);
            align-self: flex-start;
            border-bottom-left-radius: 4px;
        }

        .message.user {
            background-color: var(--user-message-bg);
            color: var(--user-message-text);
            align-self: flex-end;
            border-bottom-right-radius: 4px;
        }

        .message-icon {
            font-weight: bold;
            margin-right: 0.5rem;
        }

        .message-bubble {
            padding: 0.5rem 0;
        }

        .typing-indicator {
            display: flex;
            align-items: center;
            gap: 0.25rem;
            padding: 0.75rem 1rem;
            background: white;
            border-radius: var(--border-radius);
            align-self: flex-start;
            max-width: 150px;
        }

        .typing-dot {
            width: 8px;
            height: 8px;
            background-color: var(--typing-indicator-color);
            border-radius: 50%;
            animation: typing 1.4s infinite ease-in-out both;
        }

        .typing-dot:nth-child(1) { animation-delay: 0s; }
        .typing-dot:nth-child(2) { animation-delay: 0.2s; }
        .typing-dot:nth-child(3) { animation-delay: 0.4s; }

        @keyframes typing {
            0% { transform: scale(0.8); opacity: 0.7; }
            50% { transform: scale(1); opacity: 1; }
            100% { transform: scale(0.8); opacity: 0.7; }
        }

        .input-container {
            background: white;
            border-radius: 0 0 var(--border-radius) var(--border-radius);
            box-shadow: var(--box-shadow);
            padding: 1.5rem;
            border-top: 1px solid var(--light-gray);
        }

        .form-control {
            border-radius: var(--border-radius);
            border: 1px solid #ced4da;
            padding: 0.75rem 1rem;
            font-size: 1rem;
            transition: all 0.3s ease;
        }

        .btn {
            border-radius: var(--border-radius);
            padding: 0.75rem 1.5rem;
            font-size: 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }

        .btn-secondary {
            background-color: #6c757d;
            border-color: #6c757d;
        }

        /* 简历分析卡片 */
        .resume-analysis-card {
            background: white;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            padding: 1.5rem;
            margin-top: 1rem;
        }

        .analysis-item {
            margin-bottom: 1rem;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .interview-container {
                height: calc(100vh - 200px);
                margin-top: 1rem;
                margin-bottom: 1rem;
            }
            .message {
                max-width: 85%;
                padding: 0.75rem;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="container">
            <h1>AI模拟面试</h1>
            <div class="header-info">
                <span th:text="${jobTitle}"></span>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="interview-container">
            <div class="interview-info">
                <div class="row">
                    <div class="col-md-8">
                        <h2 class="h5 mb-0">面试岗位: <span th:text="${jobTitle}"></span></h2>
                        <div class="interview-timer">
                            <i class="bi bi-clock"></i> 面试时长: <span id="interview-timer">00:00</span>
                        </div>
                    </div>
                    <div class="col-md-4 text-md-right">
                        <span class="badge bg-primary">进行中</span>
                    </div>
                </div>
            </div>

            <div class="chat-container">
                <div class="chat-messages" id="chat-messages">
                    <!-- 初始AI问题 -->
                    <div class="message ai">
                        <div class="message-icon">AI</div>
                        <div class="message-bubble">
                            <p th:text="${questions[0]}"></p>
                        </div>
                    </div>
                </div>

                <div class="input-area">
                    <form id="answer-form">
                        <div class="form-group mb-3">
                            <textarea class="form-control" id="answer" rows="3" placeholder="请输入您的回答..." required></textarea>
                        </div>
                        <div class="text-end">
                            <button type="button" id="skip-question" class="btn btn-secondary">跳过此问题</button>
                            <button type="submit" class="btn btn-primary">提交回答</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>


    </div>

    <script>
        // 全局变量
        let interviewId = "";
        let currentQuestionIndex = 0;
        let startTime = new Date();
        let timerInterval;
        let interviewActive = true; // 定义面试活动状态变量并设置为true

        // 页面加载完成后初始化
        $(document).ready(function() {
            // 获取页面上的数据
           interviewId = [[${interviewId} ?: '']];
            
            // 启动计时器
            startInterviewTimer();

            // 表单提交处理
            $('#answer-form').submit(function(event) {
                event.preventDefault();
                handleAnswerSubmission();
            });

            // 跳过问题处理
            $('#skip-question').click(function() {
                if (confirm('确定要跳过这个问题吗？')) {
                    handleAnswerSubmission(true); // true表示跳过
                }
            });

            // 自动滚动到最新消息
            scrollToBottom();
        });

        // 处理回答提交
        function handleAnswerSubmission(skip = false) {
            if (!interviewActive) {
                return;
            }

            // 获取用户回答
            let userAnswer = skip ? "(跳过了这个问题)" : $('#answer').val().trim();

            if (!skip && (userAnswer === null || userAnswer === '')) {
                alert('请输入您的回答');
                return;
            }

            // 禁用表单防止重复提交
            $('#answer-form :input, #answer-form button').prop('disabled', true);

            // 添加用户回答到聊天区域
            addUserMessage(userAnswer);

            // 清空输入框
            $('#answer').val('');

            // 添加AI正在输入的指示
            addTypingIndicator();

            // 发送请求获取下一个问题
            $.ajax({
                url: '/new-interview/generate-next-question',
                type: 'POST',
                data: {
                    interviewId: interviewId,
                    currentQuestionIndex: currentQuestionIndex
                },
                dataType: 'json',
                beforeSend: function() {
                    // 在发送请求前保存用户答案
                    saveUserAnswer(interviewId, currentQuestionIndex, userAnswer);
                },
                success: function(response) {
                    // 移除输入指示
                    removeTypingIndicator();

                    if (typeof response === 'string') {
                        alert(response);
                        // 启用表单
                        $('#answer-form :input, #answer-form button').prop('disabled', false);
                        return;
                    }

                    // 检查是否已经回答了3个问题
                    if (response.questionIndex >= 4) {
                        // 面试结束，显示完成消息
                        addAIMessage('面试已完成，感谢您的参与！');
                        
                        // 延迟跳转到结果页面
                        setTimeout(function() {
                            window.location.href = '/new-interview/submit-answers?interviewId=' + interviewId;
                        }, 3000);
                    } else if (response.question) {
                        // 添加下一个问题
                        setTimeout(function() {
                            addAIMessage(response.question);
                            currentQuestionIndex = response.questionIndex;
                            // 启用表单
                            $('#answer-form :input, #answer-form button').prop('disabled', false);
                        }, 800); // 延迟显示，模拟思考时间
                    } else {
                        // 显示错误消息并启用表单，而不是直接结束面试
                        console.error('获取下一个问题失败，没有返回有效的问题');
                        alert('获取下一个问题失败，请刷新页面重试');
                        
                        // 启用表单
                        $('#answer-form :input, #answer-form button').prop('disabled', false);
                    }
                },
                error: function(xhr, status, error) {
                    // 移除输入指示
                    removeTypingIndicator();
                    
                    console.error('获取下一个问题失败:', error);
                    alert('获取下一个问题失败，请重试');
                    
                    // 启用表单
                    $('#answer-form :input, #answer-form button').prop('disabled', false);
                }
            });
        }

        // 添加AI消息
        function addAIMessage(message) {
            const messageElement = `
                <div class="message ai">
                    <div class="message-icon">AI</div>
                    <div class="message-bubble">
                        <p>${escapeHtml(message)}</p>
                    </div>
                </div>
            `;
            $('#chat-messages').append(messageElement);
            scrollToBottom();
        }

        // 添加用户消息
        function addUserMessage(message) {
            const messageElement = `
                <div class="message user">
                   <div class="message-bubble">
                        <p>${escapeHtml(message)}</p>
                    </div>
                    <div class="message-icon">你</div>
                </div>
            `;
            $('#chat-messages').append(messageElement);
            scrollToBottom();
        }

        // 保存用户答案
        function saveUserAnswer(interviewId, questionIndex, answer) {
            $.ajax({
                url: '/new-interview/save-answer',
                type: 'POST',
                data: {
                    interviewId: interviewId,
                    questionIndex: questionIndex,
                    answer: answer
                },
                success: function(response) {
                    console.log('答案保存成功');
                },
                error: function(xhr, status, error) {
                    console.error('保存答案失败:', error);
                }
            });
        }

        // 添加输入指示
        function addTypingIndicator() {
            const typingElement = `
                <div class="message ai" id="typing-indicator">
                    <div class="message-icon">AI</div>
                    <div class="typing-indicator">
                        <span></span>
                        <span></span>
                        <span></span>
                    </div>
               </div>
            `;
            $('#chat-messages').append(typingElement);
            scrollToBottom();
        }

        // 移除输入指示
        function removeTypingIndicator() {
            $('#typing-indicator').remove();
        }

        // 滚动到底部
        function scrollToBottom() {
            const chatMessages = document.getElementById('chat-messages');
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        // 启动面试计时器
        function startInterviewTimer() {
            timerInterval = setInterval(function() {
                const now = new Date();
                const elapsed = Math.floor((now - startTime) / 1000);
                const minutes = Math.floor(elapsed / 60).toString().padStart(2, '0');
                const seconds = (elapsed % 60).toString().padStart(2, '0');
                document.getElementById('interview-timer').textContent = `${minutes}:${seconds}`;
            }, 1000);
        }

        // HTML转义
        function escapeHtml(text) {
            if (!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // 监听窗口关闭事件，显示提示
        window.addEventListener('beforeunload', function(e) {
            if (interviewActive) {
                const confirmationMessage = '您的面试正在进行中，确定要离开吗？';
                e.returnValue = confirmationMessage;
                return confirmationMessage;
            }
        });
    </script>
</body>
</html>